package com.sphd.Restaurant.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.sphd.Restaurant.R;
import com.sphd.Restaurant.base.BaseActivity;
import com.sphd.Restaurant.interfFace.LocationInterface;
import com.sphd.Restaurant.utils.AppManager;
import com.sphd.Restaurant.utils.Constants;
import com.sphd.Restaurant.utils.LocationUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class StartActivity extends BaseActivity implements LocationInterface {
    LocationUtil locationUtil;
    Handler handler;
    Runnable runnable;
    List<String> imeis;
    boolean isBoss = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        AppManager.getAppManager().addActivity(this);
        imeis = new ArrayList<>();
        imeis.add("869372021375467");
        imeis.add("869372021481505");
        imeis.add("862873026361607");
        imeis.add("866326023726872");
        StartActivityPermissionsDispatcher.onSuccedWithCheck(this);

    }

    private void beginLoc() {
        Log.e("QI", "QI====================");
        //正式的推送Key
        showDialog();
        PushManager.startWork(context,
                PushConstants.LOGIN_TYPE_API_KEY, "ULZTTn6Ojdg0ruPdaevHvgDc");
        locationUtil = new LocationUtil(context);
        locationUtil.setLocationInterface(this);
        locationUtil.initLocation();
        locationUtil.startLocation();

    }

    @Override
    public void getLocation(AMapLocation loc) {
        if (loc != null)
            if (loc.getErrorCode() == 0) {
                if (loc.getLongitude() != 0 && loc.getLatitude() != 0) {
                    putString(Constants.LOT, String.valueOf(loc.getLongitude()));
                    putString(Constants.LAT, String.valueOf(loc.getLatitude()));
                }
                if (!TextUtils.isEmpty(loc.getAddress())) {
                    putString(Constants.ADS, loc.getAddress());
                    Log.e("add", loc.getAddress());
                } else {
                    putString(Constants.ADS, "暂无定位信息");
                }
                if (!TextUtils.isEmpty(loc.getCity())) {
                    putString(Constants.CTY, loc.getCity());
                    removeKey(Constants.LASTCITY);
                }
                toMain();
            } else {
                toMain();
            }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("onDestroy==", "onDestroy");
        if (locationUtil != null) {
            if (locationUtil.getLocationClient() != null) {
                locationUtil.stopLocation();
                locationUtil.destroyLocation();
            }
        }
        if (handler != null) {
            handler.removeCallbacks(runnable);
        }
        AppManager.getAppManager().finishActivity(this);
    }

    private void toMain() {
        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {
                dissMissDialog();
                locationUtil.stopLocation();
                locationUtil.destroyLocation();
                startActivity(MainActivity.class, new Bundle());
                AppManager.getAppManager().finishActivity(StartActivity.this);
            }
        };
        handler.postDelayed(runnable, 3500);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @NeedsPermission({
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onSucced() {
        Log.e("OK====", "授权OK");
        beginLoc();
        initBoss();
    }

    private void initBoss() {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String IMSI = telephonyManager.getDeviceId();
        removeKey(Constants.ISBOSS);
        for (int i = 0; i < imeis.size(); i++) {
            if (IMSI.equals(imeis.get(i))) {
                isBoss = true;
                break;
            }
        }

        if (isBoss) {
            if (contains(Constants.SERVICE)) {
                toast(getString(Constants.SERVICE));
            }
            putBoolean(Constants.ISBOSS, isBoss);
        } else {
            putString(Constants.SERVICE,"正式服");
            putString(Constants.SERVICEURL,"http://restaurant.zhongxs.com/Restaurant/cg/");
            putString(Constants.SERVICEBASEURL, "http://restaurant.zhongxs.com/Restaurant");
//            putString(Constants.SERVICE, "测试服");
//            putString(Constants.SERVICEURL, "http://cake.zhongxs.com/Restaurant/cg/");
//            putString(Constants.SERVICEBASEURL, "http://cake.zhongxs.com/Restaurant");


//
//            remeber.edit().putString("service", "本地服").commit();
//            remeber.edit().putString("serviceUrl", "http://192.168.1.127:8080/Restaurant/cg/").commit();
//            remeber.edit().putString("serviceBaseUrl", "http://192.168.1.127:8080/Restaurant").commit();


        }


    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        StartActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE})
    void onCause(final PermissionRequest request) {
        Log.e("onCause====", "为什么要授权");
        giveMsg(request);

    }

    private void giveMsg(PermissionRequest request) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("提示");
        builder.setMessage("应用运行需获取定位、电话信息。请许可授权");
        // 拒绝, 退出应用
        builder.setNegativeButton("算了吧", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
//                request.cancel();
                AppManager.getAppManager().finishActivity(StartActivity.this);
            }
        });

        builder.setPositiveButton("去授权", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                request.proceed();
            }
        });

        builder.setCancelable(false);
        builder.show();
    }

    @OnPermissionDenied({
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onBreak() {
        showHelp();
        Log.e("onBreak====", "拒绝了授权");
    }

    private void showHelp() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.help);
        builder.setMessage(R.string.string_help_text);

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.quit, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                AppManager.getAppManager().finishActivity(StartActivity.this);
            }
        });

        builder.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppSettings();
            }
        });

        builder.setCancelable(false);

        builder.show();
    }

    @OnNeverAskAgain({
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onNever() {
        showHelp();
        Log.e("onNever====", "不再提示");
    }
}
